package core

import (
	"bufio"
	"encoding/json"
	"log"
	"os"
	"strings"
)

type FileWatchData struct {
	Path string `json:"path"`
	Msg  string `json:"msg"`
	Time string `json:"time"`
}

var DataList []*FileWatchData = make([]*FileWatchData, 0, 10)

const LOG_FILE = "fs-status.log"

func fileExist(path string) bool {
	_, err := os.Stat(path)
	if os.IsNotExist(err) {
		return false
	}
	return true
}

// 保存数据，追加保存
func saveToFile(path string, fwd *FileWatchData) {
	var f *os.File
	var err error
	if fileExist(path) {
		f, err = os.OpenFile(path, os.O_WRONLY|os.O_APPEND, 0666)
	} else {
		f, err = os.Create(path)
	}

	if err != nil {
		log.Println("日志保存失败", err)
	}

	defer f.Close()
	write := bufio.NewWriter(f)
	line, _ := json.Marshal(*fwd)
	write.Write(line)
	write.WriteString("\n")
	write.Flush()
}

// 从文件中读取所有数据
func loadAllDataFromFile(path string) {
	if !fileExist(path) {
		return
	}

	bytes, err := os.ReadFile(path)
	if err != nil {
		log.Println("日志文件读取失败")
		return
	}

	tmp := string(bytes)
	lines := strings.Split(tmp, "\n")

	DataList = make([]*FileWatchData, 0, len(lines))

	for k := range lines {
		t := lines[k]
		if t == "" {
			continue
		}

		var data FileWatchData
		err := json.Unmarshal([]byte(t), &data)

		if err != nil {
			log.Println("日志反解析失败", t)
			continue
		}
		DataList = append(DataList, &data)
	}
}
